<?php
	if (!isset($_COOKIE['cookieid'])) {
		header("Location: index.php");
	}
	$user_id = $_COOKIE['cookieid'];
	require_once('con_db.php.inc');
	
	$is_edit = $_GET['is_edit'];
	$thumb_id = $_GET['tID'];
	$from = $_GET['from'];
	$lat = $_GET['lat'];
	$lng = $_GET['lng'];
	$datetime = $_GET['datetime'];
	$theme_id = $_GET['theme_id'];
	
	$query = "SELECT * FROM theme";
	$data = mysql_query($query, $db)
		or die('theme table에서 가져오는 쿼리 실패');
	$themes = array();
	while ($row = mysql_fetch_array($data)) {
		$themes[$row['id']] = $row['name'];
	}

	$output_form = false;
	if (isset($_POST['submit'])) {
		$title = $_POST['title'];
		$theme_id = $_POST['theme'];
		$datetime = $_POST['datetime'];
		$address = $_POST['address'];
		if (isset($_POST['address2']) && !empty($_POST['address2']))
			$address .= ' '.$_POST['address2'];
		$latitude = $_POST['latitude'];
		$longitude = $_POST['longitude'];
		$text = $_POST['text'];
		$is_public = $_POST['permission'];
		$is_edit = $_POST['is_edit'];
		$thumb_id = $_POST['tID'];
		
		// 여러가지 유효성 검증 후 전송처리
		if (empty($title)) {
			echo "제목을 입력하세요.\n";
			$output_form = true;
		}
		if (empty($datetime)) {
			echo "날짜와 시간을 입력하세요.\n";
			$output_form = true;
		}
		if (empty($address) && empty($latitude) && empty($longitude)) {
			echo "주소나 위도경도를 입력하세요.\n";
			$output_form = true;
		}
		if (empty($text)) {
			echo "본문을 입력하세요.\n";
			$output_form = true;
		}
		if ($output_form == false) {
			$datetime = date('Y-m-d H:i:s', strtotime($datetime));
			$now = date('Y-m-d H:i:s', time());
			if ($is_edit)
				$query = "UPDATE thumb SET location='$address', meetingtime='$datetime', meetingtype='$theme_id', title='$title', text='$text', is_public='$is_public', latitude='$latitude', longitude='$longitude' WHERE tID = $thumb_id";
			else
				$query = "INSERT INTO `join_here`.`thumb` (`location`, `createtime`, `meetingtime`, `meetingtype`, `title`, `text`, `tmID`, `is_public`, `latitude`, `longitude`) VALUES ('$address', '$now', '$datetime', '$theme_id', '$title', '$text', '$user_id', '$is_public', '$latitude', '$longitude');";
			mysql_query($query, $db)
				or die('엄지데이터 데이터베이스에 삽입/수정 실패');
				
			echo '<script>opener.return_data.value = "yeah";</script>';
		}
	}
	else {
		$output_form = true;
	}
	if ($output_form) {
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>엄지 폼</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript" src="http://apis.daum.net/maps/maps2.js?apikey=fdedf555ead724e65234ad4eb1ccb6760c6a6f1a"></script>
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/ui.datetimepicker.js"></script>
<link rel="stylesheet" type="text/css" href="css/dark.datetimepicker.css" />
<script type="text/javascript">
	$(document).ready(function() {
		$("#datetime").datetimepicker({dateFormat: 'yy-mm-dd', dayNamesMin: ['일', '월', '화', '수', '목', '금', '토']});
	});
	var geocoder = new google.maps.Geocoder();
	function openPopup(path, name, width, height) {
		return window.open(path, name, "width=" + width.toString() + ", height=" + height.toString() + ", menubar=no, toolbar=no");
	}
	function syncWithAddress(form) {
		var address = form["address"].value + " " + form["address2"].value;
		if (!address)
			return;
		geocoder.geocode( {'address': address }, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var validIndex;
				for (validIndex = 0; validIndex < results.length; validIndex++) {
					if (results[validIndex].geometry.location.lat() >=0 && results[validIndex].geometry.location.lng() >= 0) {
						//alert(results[validIndex].geometry.location.toString());
						break;
					}
				}
				if (validIndex >= results.length) {
					alert("검색결과가 없습니다");
					return;
				}
				form["latitude"].value = results[validIndex].geometry.location.lat();
				form["longitude"].value = results[validIndex].geometry.location.lng();
				form["text"].focus();
			}
			else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
				alert("검색결과가 없습니다");
				return;
			}
			else
				alert("주소검색 중 네트워크 문제가 발생했습니다. 다시 입력해주세요");	
		});
	}
	function syncWithLatLng(addressElem, lat, lng) {
		geocoder.geocode( {'latLng': new google.maps.LatLng(lat, lng) }, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var validIndex;
				for (validIndex = 0; validIndex < results.length; validIndex++) {
					if (results[validIndex].formatted_address) {
						//alert(results[validIndex].geometry.location.toString());
						break;
					}
				}
				if (validIndex >= results.length) {
					alert("검색결과가 없습니다");
					return;
				}
				addressElem.value = results[validIndex].formatted_address;
			}
			else if (status == google.maps.GeocoderStatus.ZERO_RESULTS) {
				alert("검색결과가 없습니다");
				return;
			}
			else
				alert("주소검색 중 네트워크 문제가 발생했습니다. 다시 입력해주세요");	
		});
	}
	function initialize() {
	<?php
		if ($is_edit) {
			if (empty($thumb_id))
				exit('thumb_id 가 null임');
				
			$query = "SELECT * FROM thumb WHERE tID = $thumb_id";
			$data = mysql_query($query, $db)
				or die("$thumb_id 로 엄지데이터 가져오기 실패");
			if (mysql_num_rows($data) != 1)
				exit("$thumb_id 로 1개 이상의 데이터가 존재");
			
			$row = mysql_fetch_array($data);
			$title = $row['title'];
			$theme_id = $row['meetingtype'];
			$datetime = $row['meetingtime'];
			$address = $row['location'];
			$latitude = $row['latitude'];
			$longitude = $row['longitude'];
			$text = $row['text'];
			$is_public = $row['is_public'];
			if ($is_public)
				echo 'document.getElementById("p_all").checked = true;';
			else
				echo 'document.getElementById("p_fr").checked = true;';
		}
		else {
			if ($from == 'map') {
				echo "document.getElementById('latitude').value = $lat;".
						"document.getElementById('longitude').value = $lng;";
				echo "syncWithLatLng(document.getElementById('address'), $lat, $lng);";
				
			}
			else if ($from == 'cal') {
				echo 'document.getElementById("datetime").value = '.date('Y-m-d H:i', $datetime).';'.
						'document.getElementById("datetime").readOnly = true;';
			}
			else if ($from == 'theme') {
				echo "var themeCombo = document.getElementById('theme');".
						"for (var i = 0; i < themeCombo.options.length; i++)".
							"if (themeCombo.options[i].value == $theme_id)".
								"themeCombo.selectedIndex = i;".
						"themeCombo.readOnly = true;";
			}
			else {
				//exit('from 인자가 없습니다');
			}
		}
	?>
	}
	function handleClickDateTime(datetime) {
		if (!datetime.value)
			return;
		$("#datetime").datepicker("setDate", new Date(datetime));
	}
</script>
</head>
<body onload="initialize()">
	<form name="thumb_form" id="thumb_form" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
		<table>
			<tr>
				<th>제목</th>
				<td><input type="text" name="title" id="title" size=30 value="<?php echo $title ?>" /></td>
			</tr>
			<tr>
				<th>테마</th>
				<td>
					<select name="theme" id="theme">
					<?php
						foreach ($themes as $key => $value) {
							if ($is_edit && $key == $theme_id)
								echo "<option selected value=$key>$value</option>";
							else
								echo "<option value=$key>$value</option>";
						}
					?>
					</select>
				</td>
			</tr>
			<tr>
				<th>시간</th>
				<td><input type="text" name="datetime" id="datetime" size=30 onclick="handleClickDateTime(this)" value="<?php echo $datetime ?>" /></td>
			</tr>
			<tr>
				<th>주소</th>
				<td>
					<input readonly type="text" name="address" id="address" size=50 value="<?php echo $address ?>" /> <input type="button" value="찾기" onclick="openPopup('thumb_postcode.php', 'postcode', 320, 240)"> <br />
					상세주소 <input type="text" name="address2" id="address2" size=30 onblur="syncWithAddress(this.form)"/>
				</td>
			</tr>
			<tr>
				<th>위도와 경도</th>
				<td>
					위도: <input readonly type="text" name="latitude" id="latitude" size=10 value="<?php echo $latitude ?>" /> 경도: <input readonly type="text" name="longitude" id="longitude" size=10 value="<?php echo $longitude ?>" />
					<input type="button" value="찾기" onclick="openPopup('select_address.php', 'select_address', 810, 650)" />
				</td>
			</tr>
			<tr>
				<th>본문</th>
				<td><textarea cols=80 rows=30 id="text" name="text"><?php echo $text ?></textarea></td>
			</tr>
			<tr>
				<th>공개</th>
				<td>
					<input checked type="radio" name="permission" id="p_all" value=1 /><label for="p_all">전체</label> <input type="radio" name="permission" id="p_fr" value=0 /><label for="p_fr">친구만</label></td>
			</tr>
			<tr>
				<th>입력</th>
				<td><input type="submit" name="submit" value="완료" /></td>
			</tr>
		</table>
		<input type="hidden" name="tID" id="tID" value=<?php echo $thumb_id ?> />
		<input type="hidden" name="is_edit" id="is_edit" value=<?php echo (isset($is_edit) && $is_edit) ? 1 : 0 ?> />
	</form>
</body>
</html>
<?php
	}
?>